<template>
  <div>
    <el-dialog v-if="dialogVisible && fileType != 'image'" title="文件预览" :visible.sync="dialogVisible" width="90vw"
               custom-class="file-preview-dialog"
               @close="handleClose">
      <!-- PDF -->
      <!--            <div class="pdf-file" v-else-if="fileType === 'pdf'">-->
      <!--                <div class="opts">-->
      <!--                    <el-button @click="previousPage" :disabled="currentPage === 1">上一页</el-button>-->
      <!--                    <el-button @click="nextPage" :disabled="currentPage === numPages">下一页</el-button>-->
      <!--                    <el-button @click.stop="clock">顺时针</el-button>-->
      <!--                    <el-button @click.stop="counterClock">逆时针</el-button>-->
      <!--                    <el-button @click="scaleD">放大</el-button>-->
      <!--                    <el-button @click="scaleX">缩小</el-button>-->
      <!--                </div>-->
      <!--                <div class="pdf-container">-->
      <!--                    <pdf ref="pdf" :src="fileUrl" :page="currentPage" :rotate="pageRotate" @num-pages="setNumPages"-->
      <!--                         @progress="loadedRatio = $event" @page-loaded="currentPage = $event" @error="onPdfError"-->
      <!--                         @link-clicked="page = $event" style="width: 100%"/>-->
      <!--                </div>-->
      <!--                <p class="pages" v-if="numPages > 0"> 当前页数/总页数：{{ currentPage }}/{{ numPages }}</p>-->
      <!--                <div>进度：{{ loadedRatio * 100 }}%</div>-->
      <!--                <div class="opts">-->
      <!--                    <el-button @click="previousPage" :disabled="currentPage === 1">上一页</el-button>-->
      <!--                    <el-button @click="nextPage" :disabled="currentPage === numPages">下一页</el-button>-->
      <!--                    <el-button @click.stop="clock">顺时针</el-button>-->
      <!--                    <el-button @click.stop="counterClock">逆时针</el-button>-->
      <!--                    <el-button @click="scaleD">放大</el-button>-->
      <!--                    <el-button @click="scaleX">缩小</el-button>-->
      <!--                </div>-->
      <!--            </div>-->

      <!-- Office 文档 -->
      <!--            <div class="office-file" v-else-if="fileType === 'file'">-->
      <!--                <iframe   :key="fileUrl"-->
      <!--                        :src="`https://view.officeapps.live.com/op/view.aspx?src=${encodeURIComponent(fileUrl)}`"-->
      <!--                        frameborder="0" style="width: 100%; height: 80vh"></iframe>-->
      <!--            </div>-->


      <!-- Office 文档 - 使用 kkFileView -->
      <!--                    <div class="office-file" v-else-if="fileType === 'file'">-->
      <!--                        <iframe  :key="kkFileViewUrl" :src="kkFileViewUrl" frameborder="0" style="width: 100%; height: 80vh"></iframe>-->
      <!--                    </div>-->


      <div class="office-file" v-if=" previewUrl  && (fileType === 'file' || fileType === 'pdf')">
        <iframe  :key="iframeKey" :src="previewUrl"  @load="iframeLoaded"
                ref="iframe" frameborder="0" style="width: 100%; height: 80vh"></iframe>


      </div>


      <!-- 视频 -->
      <div class="video-file" v-else-if="fileType === 'video'">
        <video :src="fileUrl" controls style="width: 100%; max-height: 600px;">
          您的浏览器不支持 video 标签。
        </video>
      </div>

      <!-- 不支持的文件类型 -->
      <div class="unsupported" v-else>
        <p>暂不支持该文件类型的预览。</p>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import pdf from 'vue-pdf';
import {number} from "@/assets/imgs/操作_files/chunk-vendors";

let Base64 = require('js-base64').Base64;
export default {
  name: 'FilePreview',
  components: {
    pdf
  },
  props: {
    options: {
      // 图片列表
      type: Array,
      default: () => []
    },
    visible: {
      type: Boolean,
      default: false
    },
    url: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      dialogVisible:false,
      iframeKey:0,
      rlen: history.length,
      imgList: [],
      currentIndex: 0, // 当前图片索引
      viewerInstance: null, // 存储 viewer 实例
      pdfSrc: null,
      currentPage: 1,
      numPages: 0,
      loadedRatio: 0,
      fileType: 'unknown', // image / pdf / file / video / unknown
      pdfError: false,
      scale: 100, // 放大系数 默认百分百
      pageRotate: 0, // 旋转角度 ‘90’的倍数才有效
    };
  },
  computed: {
    // dialogVisible: {
    //   get() {
    //     return this.visible; // ✅ 双向绑定 visible
    //   },
    //   set(val) {
    //     this.$emit('update:visible', val); // ✅ sync 机制
    //   }
    // },
    previewUrl() {
      if (!this.url) return '';

      if (/\.(pdf)$/i.test(this.url.split('?')[0])) {
        return 'https://wmzh.life-oasis.com/kkFileView/onlinePreview?url=' + encodeURIComponent(Base64.encode(this.url)) + "&officePreviewType=pdf";
      }


      // console.log('https://wmzh.life-oasis.com/kkFileView/onlinePreview?url=' + encodeURIComponent(Base64.encode(this.url)))
      return 'https://wmzh.life-oasis.com/kkFileView/onlinePreview?url=' + encodeURIComponent(Base64.encode(this.url));
    },


  },


  // watch: {
  //
  //   dialogVisible(val) {
  //     if (val) {
  //       this.iframeKey++; // 每次打开弹窗，iframe 重新加载
  //       // 弹窗打开时，重新加载
  //       this.handleUrlChange(this.url);
  //     }
  //   },
  //
  //   url: {
  //     handler(newUrl) {
  //       if (this.dialogVisible) {
  //         console.log("newUrl", newUrl);
  //         this.handleUrlChange(newUrl);
  //       }
  //     }
  //   }
  // },
  methods: {
    openModal() {
      this.dialogVisible = true;
      this.$nextTick(() => {
        console.log("openModal",this.url);
        this.handleUrlChange(this.url);
      })
    },

    handleUrlChange(newUrl){

      this.fileType = this.getFileTypeFromUrl(newUrl);

      if (this.fileType == 'image') {
        // 设置图片列表
        // 过滤 options：只保留确实是图片的对象
        const imageFiles = this.options
            ? this.options.filter(option => {
              const type = this.getFileTypeFromUrl(option.url);
              return type === 'image';
            })
            : [];

        // // 如果当前文件不在 options 中，也要包含它
        // const newFile = {url: newUrl, fileName: newFileName};
        // if (!imageFiles.some(file => file.url === newFile.url)) {
        //     imageFiles.unshift(newFile); // 或 push，根据顺序需求
        // }

        this.imgList = imageFiles;

        // 找到当前图片在 imgList 中的索引
        let initialIndex = this.imgList.findIndex(file => file.url === newUrl);
        if (initialIndex === -1) {
          // 如果没有找到，可能是由于某种原因该URL不在列表中，这时可以设置为0或者处理错误。
          initialIndex = 0;
        }

        this.$viewerApi({
          images: this.imgList.map(img => img.url), // 提供纯URL数组给images
          options: {
            initialViewIndex: initialIndex, // 设置初始显示的图片索引
            title: function (imageElement, imageData) {
              // 查找对应的 fileName 并返回作为标题
              const file = this.imgList.find(img => img.url === imageElement.src);
              return file ? file.fileName : '未知图片';
            }.bind(this)
          }
        });


      }

    },

    iframeLoaded(e) {
      // if(!this.isFirst){
      //     console.log("第一次")
      //     this.isFirst = true;
      // }else {
      //     // this.rlen = this.rlen + 1;//-1是不进入iframe页面的下级页面直接退出的话，执行后退一步的操作
      //     console.log("不是第一次")
      // }
      console.log(history.length)
      console.log("iframe loaded", e)
    },
    //放大
    scaleD() {
      this.scale += 5;
      this.$refs.pdf.$el.style.width = parseInt(this.scale) + "%";
    },

    // 顺时针选中角度
    clock() {
      this.pageRotate += 90;
    },
    // 逆时针旋转角度
    counterClock() {
      this.pageRotate -= 90;
    },

    //缩小
    scaleX() {
      // scale 是百分百展示 不建议缩放
      if (this.scale == 100) {
        return;
      }
      this.scale += -5;
      console.log(parseInt(this.scale) + "%");
      this.$refs.pdf.$el.style.width = parseInt(this.scale) + "%";
    },


    getFileTypeFromUrl(url) {
      const match = url.match(/\.([0-9a-z]+)(?:[\?#]|$)/i);
      const ext = match ? match[1].toLowerCase() : '';

      const imageExts = ['jpg', 'jpeg', 'png', 'gif'];
      const pdfExts = ['pdf'];
      const officeExts = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'];
      const videoExts = ['mp4', 'webm', 'ogg'];

      if (imageExts.includes(ext)) return 'image';
      if (pdfExts.includes(ext)) return 'pdf';
      if (officeExts.includes(ext)) return 'file';
      if (videoExts.includes(ext)) return 'video';

      return 'file';
    },

    handleClose() {

      let len = this.rlen - history.length - 1;//-1是不进入iframe页面的下级页面直接退出的话，执行后退一步的操作
      console.log("应该跳转", this.rlen, history.length, len)
      if (len != 0) {
        console.log("跳转", len, typeof len)
        // this.$router.go(len)
      }

      this.fileType = '';
      this.imgList = [];
      this.$emit('update:visible', false);
      // console.log("chua")
      // this.$emit('closeNum',len)

      let num = sessionStorage.getItem("pageNum");
      // alert("当前" + num)

      if (num != null && Number(num) != -1) {
        // alert("相加" + (Number(len) + Number(num)))
        sessionStorage.setItem("pageNum", Number(len) + Number(num)+1);
      } else {
        // alert("设置len" + len)
        sessionStorage.setItem("pageNum", len);
        this.dialogVisible=false
      }


    },
    setNumPages(numPages) {
      this.numPages = numPages;
    },

    nextPage() {
      if (this.currentPage < this.numPages) {
        this.currentPage++;
      }
    },
    onPdfError(error) {
      console.error('PDF 加载失败：', error);
      this.pdfError = true;
    },


    previousPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
      }
    },
    loadPdf() {
      this.pdfSrc = pdf.createLoadingTask(this.url);
      this.pdfSrc.promise.then(pdf => {
        this.setNumPages(pdf.numPages);
      }).catch(error => {
        this.onPdfError(error);
      });
    }
  },
  mounted() {
    console.log("mounted")
    // if (this.visible && this.fileType === 'pdf') {
    //     // 初始化 PDF 查看器
    //     this.loadPdf();
    //
    //     // const viewer = this.$refs.pdfViewer;
    //     // if (viewer && viewer.pdf) {
    //     //   viewer.pdf.then(pdf => {
    //     //     this.numPages = pdf.numPages;
    //     //   });
    //     // }
    // }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .file-preview-dialog {
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-width: 90vw;
  max-height: 98vh;
  display: flex;
  flex-direction: column;
  align-items: center;

  .el-dialog__body {
    flex: 1;
    overflow: auto;
    padding: 0;
    width: 100%;
  }


  .pdf-file,
  .office-file,
  .video-file,
  .unsupported {
    text-align: center;
  }

  .pdf-file {
    width: 60vw;
    margin: auto;
  }

  .image {
    margin-bottom: 30px;

    span {
      color: #666;
      display: block;
      width: 100%;
      text-align: center;
    }
  }

  .el-image {
    max-width: 500px;
    display: block;
    margin: auto;
  }

  .pdf-container {
    width: 100%;
    margin: auto;
    overflow-y: auto;
    border: 1px solid #e4e4e4;
    padding: 10px;
  }

  .pages {
    margin-top: 10px;
  }

  .opts {
    margin-top: 15px;
  }
}


.viewer-trigger {
  cursor: pointer;
  display: inline-block;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
  transition: box-shadow 0.3s;

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
}

.main-img {
  max-width: 100%;
  max-height: 600px;
  object-fit: contain;
}

</style>
